package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.factory.UserDeptOptionalRangeFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.field.LimitChooseRangePoJo;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.optional.range.UserDeptOptionalRangeHandler;
import com.xbongbong.paas.pojo.dto.DepartmentFlatListDTO;
import com.xbongbong.paas.pojo.dto.DepartmentGetDTO;
import com.xbongbong.paas.pojo.dto.DepartmentListDTO;
import com.xbongbong.paas.pojo.dto.DepartmentSimpleListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.UserInfoDTO;
import com.xbongbong.paas.pojo.vo.DepartmentFlatListVO;
import com.xbongbong.paas.pojo.vo.DepartmentGetVO;
import com.xbongbong.paas.pojo.vo.DepartmentListVO;
import com.xbongbong.paas.pojo.vo.DepartmentSimpleListVO;
import com.xbongbong.paas.service.DepartmentService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.DepartmentVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import com.xbongbong.pro.department.pojo.dto.DepartmentListRelatedDTO;
import com.xbongbong.pro.department.pojo.dto.DepartmentUserListDTO;
import com.xbongbong.pro.department.pojo.vo.DepartmentListRelatedVO;
import com.xbongbong.pro.department.pojo.vo.DepartmentUserListVO;
import com.xbongbong.pro.enums.LimitChooseRangeTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ProductUserEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductUserModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserDepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserDepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @time 2018-9-10 13:34
 */
@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {

    private static final Logger LOG = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private UserDepartmentModel userDepartmentModel;
    @Resource
    private ProductUserModel productUserModel;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasFormDataModel paasFormDataModel;


    /**
     * 是否从缓存内读取标记：false-不从缓存读取，true-从缓存读取
     */
    private boolean ifJedis = false;

    @Override
    public DepartmentListVO list(DepartmentListDTO departmentListDTO) throws XbbException {
        DepartmentListVO departmentListVO = new DepartmentListVO();
        String corpid = departmentListDTO.getCorpid();
        Boolean showHidden = departmentListDTO.getShowHidden();

        departmentListVO.setCorpid(corpid);

        try {
            JSONArray departmentTree;
            if (Objects.nonNull(departmentListDTO.getLimitDep())) {
                departmentTree = getSubDept(departmentListDTO.getLoginUser(), departmentListDTO.getShowHidden(), false);
                departmentListVO.setDepartmentTree(departmentTree);
                return departmentListVO;
            }
            departmentTree = departmentModel.getDepartmentJsonTree(corpid, showHidden);
            departmentListVO.setDepartmentTree(departmentTree);
        } catch (Exception e) {
            LOG.error("departmentService.list 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return departmentListVO;
    }



    @Override
    public DepartmentFlatListVO flatList(DepartmentFlatListDTO departmentFlatListDTO) throws XbbException {
        DepartmentFlatListVO departmentFlatListVO = new DepartmentFlatListVO();
        String corpid = departmentFlatListDTO.getCorpid();
        Boolean showHidden = departmentFlatListDTO.getShowHidden();

        departmentFlatListVO.setCorpid(corpid);

        PageHelper pageHelper;
        List<DepartmentEntity> departmentList;
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(departmentFlatListDTO, true);
            /*
             * showHidden为true时显示隐藏部门（即del=2的记录），
             * 为false 时不显示隐藏部门
             */
            if (showHidden) {
                param.put("negDel", 1);
            } else {
                param.put("del", 0);
            }
            pageHelper = PageHelperUtil.getPageHelper(param, departmentModel, departmentFlatListDTO.getPageSize());
            departmentList = (List<DepartmentEntity>) PageHelperUtil.getEntityList(param, pageHelper, departmentModel);

            List<DepartmentVO> departmentVOList = new ArrayList<>();
            BeanUtil.copyPropertiesList(departmentList, departmentVOList, DepartmentVO.class);
            departmentFlatListVO.setDepartmentList(departmentVOList);
        } catch (Exception e) {
            LOG.error("departmentService.list 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return departmentFlatListVO;
    }

    @Override
    public DepartmentSimpleListVO simpleList(DepartmentSimpleListDTO simpleListDTO) throws XbbException {
        DepartmentSimpleListVO simpleListVO = new DepartmentSimpleListVO();
        String corpid = simpleListDTO.getCorpid();
        Boolean showHidden = simpleListDTO.getShowHidden();
        String attr = simpleListDTO.getAttr();
        Long formId = simpleListDTO.getFormId();
        Map<String, List<Long>> deptOptionalRange = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        simpleListVO.setCorpid(corpid);
        try {
            if (Objects.nonNull(simpleListDTO.getLimitDep())) {
                JSONArray departTree = getSubDept(simpleListDTO.getLoginUser(), showHidden, true);
                simpleListVO.setDepartmentTree(departTree);
                return simpleListVO;
            }
            //判断是否开启部门成员 可选范围
            if (StringUtil.isNotEmpty(attr) && Objects.nonNull(formId) && formId != 0L){
                PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formId, simpleListDTO.getBusinessType());
                if (Objects.nonNull(paasFormExplainEntity)) {
                    Map<String, FieldAttrEntity> explainMap = ExplainUtil.getAllSubFormExplainMap(paasFormExplainEntity.getExplains());
                    FieldAttrEntity fieldAttrEntity = explainMap.get(simpleListDTO.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)){
                        LimitChooseRangePoJo limitChooseRange = fieldAttrEntity.getLimitChooseRange();
                        if (Objects.nonNull(limitChooseRange) && Objects.equals(limitChooseRange.getType(), LimitChooseRangeTypeEnum.CUSTOM.getType())){
                            deptOptionalRange = optionalRangeFilterDept(simpleListDTO, limitChooseRange);
                            simpleListVO.setOpenRangeFilter((Objects.isNull(deptOptionalRange)) ? 0 : 1);
                        }
                    }
                }
            }
            JSONArray departmentTree;
            if (Objects.equals(simpleListVO.getOpenRangeFilter(), 1)){
                 departmentTree = departmentModel.getDepartmentSimpleJsonTree(corpid, showHidden, deptOptionalRange);
            }else {
                departmentTree = departmentModel.getDepartmentSimpleJsonTree(corpid, showHidden);
            }

            simpleListVO.setDepartmentTree(departmentTree);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("departmentService.simpleList 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return simpleListVO;
    }

    /**
     * @Description 部门范围自定义筛选
     * @return
     * @author sunshaoxiang
     * @Date  2021/9/9 5:56
     * @since
     **/
    private Map<String, List<Long>> optionalRangeFilterDept(DepartmentSimpleListDTO simpleListDTO, LimitChooseRangePoJo limitChooseRange) throws XbbException {
        List<Long> deptIdIn = null;
        List<Long> deptIdNoIn = null;
        List<ProductUserEntity> productUserList = new ArrayList<>();
        Map<String, List<Long>> deptOptionalRange = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> productUserParams = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        UserInfoDTO loginUserInfo = new UserInfoDTO();
        PaasFormDataEntity formDataEntity = new PaasFormDataEntity();
        Long productId = simpleListDTO.getDataId();
        try{
            //区分是否是新建表单数据以及排除移动端跟进记录
            if (Objects.nonNull(simpleListDTO.getDataId()) && !Objects.equals(simpleListDTO.getDataId(), 0L)
                    && !Objects.equals(simpleListDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode())){
                if (Objects.equals(simpleListDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                    formDataEntity = paasFormDataModel.getByKey(simpleListDTO.getDataId(), simpleListDTO.getCorpid());
                } else {
                    formDataEntity = saasUpdateHelp.getFormData(simpleListDTO.getDataId(), simpleListDTO.getCorpid(), simpleListDTO.getBusinessType());
                }
                if (Objects.isNull(formDataEntity)) {
                    return null;
                }
            }
            //特殊处理后端取可见部门的数据
            ProductEntityExt product = productModel.getByKey(productId, simpleListDTO.getCorpid());
            if (Objects.nonNull(product)) {
                JSONObject dataList = product.getData();
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, ProductEnum.PARENT_ID.getAttr(), 0L);
                if (!Objects.equals(parentId, 0L)) {
                    productId = parentId;
                }
                productUserParams.put(ParameterConstant.CORPID, simpleListDTO.getCorpid());
                productUserParams.put(ParameterConstant.PRODUCT_ID, productId);
                productUserParams.put("del", 0);
                productUserList = productUserModel.findEntitys(productUserParams);
            }
            loginUserInfo.setLoginUser(simpleListDTO.getLoginUser());
            if (CollectionsUtil.isNotEmpty(limitChooseRange.getFilterConditions())){
                for (FilterConditionsPoJo item : limitChooseRange.getFilterConditions()) {
                    //判断当前条件是否是部门名称条件
                    if ( Objects.isNull(item) || !Objects.equals(item.getFieldType(), FieldTypeEnum.DEPT_NAME.getType())){
                        return deptOptionalRange;
                    }
                    UserDeptOptionalRangeHandler optionalRangeHandler = UserDeptOptionalRangeFactory.getHandlerByFieldType(item.getFieldType());
                    Map<String, Object> deptMap = optionalRangeHandler.filterDeptUserData(item, simpleListDTO.getOptionalRangeDataList(),  formDataEntity, null, productUserList, loginUserInfo);
                    if (Objects.nonNull(deptMap) && Objects.nonNull(deptMap.get("deptIdIn"))){
                        if (deptMap.get("deptIdIn") instanceof List){
                            List deptIds = (List) deptMap.get("deptIdIn");
                            if (Objects.isNull(deptIdIn)){
                                deptIdIn = deptIds;
                            }else {
                                //且条件，取交集
                                deptIdIn.retainAll(deptIds);
                            }
                        }
                    }
                    if (Objects.nonNull(deptMap) && Objects.nonNull(deptMap.get("deptIdNoIn"))){
                        if (deptMap.get("deptIdNoIn") instanceof List){
                            List deptIds = (List) deptMap.get("deptIdNoIn");
                            if (Objects.isNull(deptIdNoIn)){
                                deptIdNoIn = deptIds;
                            }else {
                                deptIdNoIn.addAll(deptIds);
                                deptIdNoIn =  deptIdNoIn.stream().distinct().collect(Collectors.toList());
                            }
                        }
                    }
                }
                //等于任意一个和不等于任意一个条件都存在 取交集
                if (Objects.nonNull(deptIdIn)){
                    if (Objects.nonNull(deptIdNoIn)){
                        deptIdIn.removeAll(deptIdNoIn);
                    }
                    deptOptionalRange.put("deptIdIn", deptIdIn);
                }else {
                    deptOptionalRange.put("deptIdNoIn", deptIdNoIn);
                }
            }
            return deptOptionalRange;
        } catch (Exception e) {
            LOG.error("departmentService.optionalRangeFilterDept 执行错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }

    @Override
    public DepartmentGetVO getByDepartmentIds(DepartmentGetDTO departmentGetDTO) throws XbbException {
        DepartmentGetVO departmentGetVO = new DepartmentGetVO();
        try {
            List<DepartmentVO> departmentVOList = new ArrayList<>();
            List<DepartmentEntity> departmentEntityList = departmentModel.findEntitysByDepartmentIds(departmentGetDTO.getDepartmentIds(), departmentGetDTO.getCorpid());
            if (departmentEntityList != null) {
                departmentEntityList.forEach((item) -> {
                    DepartmentVO departmentVO = new DepartmentVO();
                    BeanUtil.copyProperties(item, departmentVO);
                    departmentVOList.add(departmentVO);
                });
            }
            departmentGetVO.setDepartmentList(departmentVOList);
        } catch (Exception e) {
            LOG.error("departmentService.get 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return departmentGetVO;
    }

    /**
     * 是否从缓存内读取标记：false-不从缓存读取，true-从缓存读取
     *
     * @param ifJedis
     */
    @Override
    public void setIfJedis(boolean ifJedis) {
        this.ifJedis = ifJedis;
    }

    /**
     * 获取某公司所有部门列表--先从缓存内获取，缓存内没有则查询数据库，然后存入缓存
     *
     * @param corpid 公司ID
     * @return
     */
    @Override
    public List<DepartmentEntity> getAllDepList(String corpid) {
        if (StringUtil.isEmpty(corpid)) {
            return null;
        }

        List<DepartmentEntity> list = null;
        if (ifJedis) {
            // TODO 等待卡特在paasRedisHelper加方法
            //list = (List<DepartmentEntity>) paasRedisHelper.getJedisValue("getAllDepList", corpid);
        }

        if (list != null) {
            return list;
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("corpid", corpid);
        param.put("del", 0);

        list = departmentModel.findEntitys(param);

        if (ifJedis) {
            // TODO 等待卡特在paasRedisHelper加方法
            // paasRedisHelper.setJedisValue("getAllDepList", corpid, list, BasicConstant.SESSION_EFFECTIVE_TIME);
        }

        return list;
    }

    @Override
    public DepartmentListRelatedVO relatedList(DepartmentListRelatedDTO departmentListRelatedDTO) throws XbbException {
        DepartmentListRelatedVO departmentListRelatedVO = new DepartmentListRelatedVO();
        try {
            List<String> userIdList = departmentListRelatedDTO.getUserIdList();
            Boolean isEmpty = Objects.isNull(userIdList) || userIdList.isEmpty();
            Boolean isCreator = Objects.equals(FieldTypeEnum.CREATORID.getAlias(), departmentListRelatedDTO.getRelatedMember())
                    || StringUtil.isEmpty(departmentListRelatedDTO.getRelatedMember());
            if (isEmpty && isCreator) {
                if (Objects.isNull(userIdList)) {
                    // 初始化
                    userIdList = new ArrayList<>();
                }
                userIdList.add(departmentListRelatedDTO.getUserId());
            } else if (isEmpty) {
                departmentListRelatedVO.setDepartmentList(new ArrayList<>());
                return departmentListRelatedVO;
            }
            List<UserEntity> userList = userModel.findEntitysByUserIds(userIdList, departmentListRelatedDTO.getCorpid());
            if (Objects.isNull(userList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            if (userList.isEmpty()) {
                departmentListRelatedVO.setDepartmentList(new ArrayList<>());
                return departmentListRelatedVO;
            }
            Set<Long> idIn = new HashSet<>();
            userList.forEach(item->{
                idIn.addAll(JSONArray.parseArray(item.getDepartment(), Long.class));
            });
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("idIn", idIn);
            param.put("corpid", departmentListRelatedDTO.getCorpid());
            /*
             * showHidden为true时显示隐藏部门（即del=2的记录），
             * 为false 时不显示隐藏部门
             */
            if (departmentListRelatedDTO.getShowHidden()) {
                param.put("negDel", 1);
            } else {
                param.put("del", 0);
            }
            List<DepartmentEntity> departmentList = departmentModel.findEntitys(param);
            if (Objects.isNull(departmentList) || departmentList.isEmpty()) {
                departmentListRelatedVO.setDepartmentList(new ArrayList<>());
                return departmentListRelatedVO;
            }
            List<DepartmentVO> resultDepartmentList = new ArrayList<>();
            departmentList.forEach(item->{
                DepartmentVO departmentVO = new DepartmentVO();
                BeanUtil.copyProperties(item, departmentVO);
                resultDepartmentList.add(departmentVO);
            });
            departmentListRelatedVO.setDepartmentList(resultDepartmentList);
        } catch (Exception e) {
            LOG.error("departmentService.relatedList 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return departmentListRelatedVO;
    }

    /**
     * 获取数据权限内的部门
     *
     * @param loginUser 登陆人
     * @param showhidden 是否展示隐藏部门
     * @param simple 是否是简单格式部门列表
     * @throws
     * @author long.rao
     * @date 2020-03-24 16:37
     */
    private JSONArray getSubDept(UserVO loginUser, Boolean showhidden, Boolean simple) throws XbbException, IllegalAccessException {
        String corpid = loginUser.getCorpid();
        String userId = loginUser.getUserId();
        JSONArray departmentTree;
        List<Long> manageDepIds = new ArrayList<>();
        List<DepartmentEntity> departmentEntities = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        if (loginUser.isAdminOrBoss() || loginUser.isMaxDataPermission(true)) {
            if (simple) {
                departmentTree = departmentModel.getDepartmentSimpleJsonTree(corpid, showhidden);
            } else {
                departmentTree = departmentModel.getDepartmentJsonTree(corpid, showhidden);
            }
            return departmentTree;
        } else if (Objects.equals(dataPermission, DataPermissionEnum.CUSTOM.getCode())) {
            // 助理的部门列表
            manageDepIds = userModel.getUserAssistDepIdList(corpid, userId);
        } else if (Objects.equals(dataPermission, DataPermissionEnum.DEPARTMENT.getCode())) {
            // 主管部门列表
            manageDepIds = userModel.getUserBelongDeptIdList(corpid, userId, true);
        } else if (Objects.equals(dataPermission, DataPermissionEnum.DEPARTMENT_RECURSION.getCode())) {
            manageDepIds = userModel.getUserBelongDeptIdList(corpid, userId, true);
            if (!manageDepIds.isEmpty()) {
                List<Long> subDepIds = departmentModel.getSubDepIdList(corpid, manageDepIds);
                manageDepIds.addAll(subDepIds);
            }
        }
        departmentEntities = departmentModel.getByDepIdIn(corpid, manageDepIds);

        List<DepartmentEntity> selectDepartmentList = new ArrayList<>();

        try {
            BeanUtil.copyPropertiesList(departmentEntities, selectDepartmentList, DepartmentEntity.class);
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        List<Long> deptIds = new ArrayList<>();
        departmentEntities.forEach(item -> {
            deptIds.add(item.getId());
        });
        Iterator<DepartmentEntity> iterator = departmentEntities.iterator();
        while (iterator.hasNext()) {
            DepartmentEntity next = iterator.next();
            String depIdRouter = next.getDepIdRouter();
            List<Long> depts = StringUtil.toLongList(depIdRouter, "\\|");
            depts.removeIf(item -> Objects.equals(next.getId(), item));
            depts.retainAll(deptIds);
            if (!depts.isEmpty()) {
                // 如果自己的部门存在上下级关系，那么去掉下级部门
                iterator.remove();
            }
        }
        departmentTree = departmentModel.getSubDeptJsonTreeByDeptId(corpid, showhidden, departmentEntities, simple, selectDepartmentList);
        return departmentTree;
    }

    @Override
    public Long verifyDepartment(ImportFormDataDTO importFormDataDTO, Map<String, FieldAttrEntity> explainMap, JSONObject dataList) throws XbbException {
        Long departmentId = dataList.getJSONObject(FieldTypeEnum.DEPARTMENTID.getAlias()).getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
        FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.DEPARTMENTID.getAlias());
        if (Objects.nonNull(fieldAttrEntity) && Objects.nonNull(departmentId)) {
            String relatedMember = fieldAttrEntity.getRelatedMember();
            Boolean isCreator = Objects.equals(FieldTypeEnum.CREATORID.getAlias(),relatedMember)
                    || StringUtil.isEmpty(relatedMember);
            List<String> userIdList = new ArrayList<>();
            if (StringUtil.isEmpty(relatedMember)) {
                relatedMember = FieldTypeEnum.CREATORID.getAlias();
            }
            FieldAttrEntity relationField = explainMap.getOrDefault(relatedMember, new FieldAttrEntity());
            if (isCreator) {
                String creatorId;
                // 数据兼容, 传入值为JSONObject或userId
                if (dataList.get(FieldTypeEnum.CREATORID.getAlias()) instanceof Map) {
                    creatorId = dataList.getJSONObject(FieldTypeEnum.CREATORID.getAlias()).getString(BusinessConstant.ID);
                } else {
                    creatorId = dataList.getString(FieldTypeEnum.CREATORID.getAlias());
                }
                if (StringUtil.isEmpty(creatorId)) {
                    creatorId = importFormDataDTO.getUserId();
                }
                userIdList.add(creatorId);
            } else {
                if (dataList.get(relatedMember) instanceof JSONArray || dataList.get(relatedMember) instanceof List) {
                    List<ReturnUserAndDepartmentPojo> mutliUserList = dataList.getJSONArray(relatedMember).toJavaList(ReturnUserAndDepartmentPojo.class);
                    mutliUserList.forEach(user -> userIdList.add(user.getId().toString()));
                }
                if (dataList.get(relatedMember) instanceof Map || dataList.get(relatedMember) instanceof ReturnUserAndDepartmentPojo) {
                    JSONObject singleUser= dataList.getJSONObject(relatedMember);
                    userIdList.add(singleUser.getString(StringConstant.SAAS_LINK_BUSINESS_ID));
                }
            }
            DepartmentListRelatedDTO departmentListRelatedDTO = new DepartmentListRelatedDTO();
            BeanUtil.copyProperties(importFormDataDTO, departmentListRelatedDTO);
            departmentListRelatedDTO.setRelatedMember(relatedMember);
            departmentListRelatedDTO.setUserIdList(userIdList);
            DepartmentListRelatedVO departmentListRelatedVO = relatedList(departmentListRelatedDTO);
            List<DepartmentVO> departmentList = departmentListRelatedVO.getDepartmentList();
            if (Objects.nonNull(departmentList)) {
                List<Long> departmentIds = new ArrayList<>();
                departmentList.forEach(department-> departmentIds.add(department.getId()));
                if (!departmentIds.contains(departmentId)) {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235021, String.format(ImportErrorCodeEnum.API_ERROR_235021.getMsg(), fieldAttrEntity.getAttrName(), Objects.toString(relationField.getAttrName(), ""), Objects.toString(relationField.getAttrName(), "")));
                }
            }
        }
        return departmentId;
    }

    @Override
    public DepartmentUserListVO departmentUserList(DepartmentUserListDTO departmentUserListDTO) throws XbbException {
        DepartmentUserListVO departmentUserListVO = new DepartmentUserListVO();
        try {
            Long departmentId = departmentUserListDTO.getDepartmentId();
            String corpid = departmentUserListDTO.getCorpid();
            List<DepartmentEntity> departmentList = departmentModel.getSubOneLevel(corpid, departmentId);
            List<DepartmentUserPojo> departmentUserList = new ArrayList<>();
            departmentList.forEach(item->{
                DepartmentUserPojo departmentUserPojo = new DepartmentUserPojo(item.getId(), item.getName(), OptionalRangeEnum.DEPT.getValue(), false);
                departmentUserList.add(departmentUserPojo);
            });
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("departmentId", departmentId);
            List<UserDepartmentEntity> userDepartmentList = userDepartmentModel.findEntitys(param);
            if (CollectionsUtil.isNotEmpty(userDepartmentList)) {
                Set<String> userIdSet = new HashSet<>();
                userDepartmentList.forEach(item->{
                    userIdSet.add(item.getUserId());
                });
                if (CollectionsUtil.isNotEmpty(userIdSet)) {
                    param.clear();
                    param.put(StringConstant.CORPID, corpid);
                    param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                    param.put("userIdIn", userIdSet);
                    List<UserEntity> userList = userModel.findEntitys(param);
                    if (CollectionsUtil.isNotEmpty(userList)) {
                        userList.forEach(item->{
                            DepartmentUserPojo departmentUserPojo = new DepartmentUserPojo(item.getUserId(), item.getName(), OptionalRangeEnum.USER.getValue(), true);
                            departmentUserList.add(departmentUserPojo);
                        });
                    }
                }
            }
            departmentUserListVO.setDepartmentUserList(departmentUserList);
        } catch (Exception e) {
            LOG.error("departmentService.departmentUserList 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return departmentUserListVO;
    }
}
